#include "QAfarsekFileList.h"
#include <QMessageBox>

//_______________________________________________________________________________
QAfarsekFileList::QAfarsekFileList(QWidget *parent) :
    QTableWidget(parent)
{
    this->setRowCount(0);
    this->setColumnCount(2);

    QStringList horizonalHeaders;
    horizonalHeaders << "Name" << "Duration";
    this->setHorizontalHeaderLabels ( horizonalHeaders );
    this->setColumnWidth(0, 86);
    //this->setRowHeight(0,30);

    m_CurrentlyEdittedName.clear();

    m_fileSystem = NULL;
    m_CurrentProgressBar = NULL;

    connect(this, SIGNAL(cellChanged(int,int)), this, SLOT(on_cellChanged(int,int)));
    connect(this, SIGNAL(cellDoubleClicked(int,int)), this, SLOT(on_cellDoubleClicked(int,int)));
    m_appearanceChanged = true;
    m_downloading = false;

    m_timer = new QTimer(this);
    connect(m_timer, SIGNAL(timeout()), this, SLOT(on_TimerUpdate()));
    m_timer->start(100);
    m_currentEdittedDevice = -1;
}

//_______________________________________________________________________________
QAfarsekFileList::QAfarsekFileList(const QAfarsekFileList& fileList)
{
    this->setRowCount(0);
    this->setColumnCount(2);

    QStringList horizonalHeaders;
    horizonalHeaders << "Name" << "Duration";
    this->setHorizontalHeaderLabels ( horizonalHeaders );
    this->setColumnWidth(0, 86);

    m_CurrentlyEdittedName = fileList.m_CurrentlyEdittedName;

    m_fileSystem = fileList.m_fileSystem;
    m_CurrentProgressBar = NULL;

    connect(this, SIGNAL(cellChanged(int,int)), this, SLOT(on_cellChanged(int,int)));
    connect(this, SIGNAL(cellDoubleClicked(int,int)), this, SLOT(on_cellDoubleClicked(int,int)));
    m_appearanceChanged = fileList.m_appearanceChanged;
    m_downloading = fileList.m_downloading;

    m_timer = new QTimer(this);
    connect(m_timer, SIGNAL(timeout()), this, SLOT(on_TimerUpdate()));
    m_timer->start(100);

    m_currentEdittedDevice = fileList.m_currentEdittedDevice;
}

//_______________________________________________________________________________
QAfarsekFileList::~QAfarsekFileList()
{
    /*if (m_CurrentProgressBar!=NULL)
    {
        delete m_CurrentProgressBar;
        m_CurrentProgressBar = NULL;
    }*/
    if (m_timer!=NULL)
        delete m_timer;
}

//_______________________________________________________________________________
void QAfarsekFileList::SetFileSystem (CFileSystem *fileSystem)
{
    m_fileSystem = fileSystem;
}

//_______________________________________________________________________________
void QAfarsekFileList::UpdateFileList ( void )
{
    m_CurrentlyEdittedName.clear();

    bool atLeastOneDownloading = false;

    if (m_fileSystem == NULL)
        return;

    file_list_t list = m_fileSystem->GetFileList();
    file_list_it_t it;
    int listSize = list.size();

    if (this->columnCount ()>0)
        this->clearContents();

    this->setRowCount(listSize);
    int rowNum = 0;

    // walk over the list of files and update the table
    for (it = list.begin(); it!=list.end(); rowNum ++, it++)
    {
        // create the first column "FILE NAME" widget
        QTableWidgetItem *newItem1 = new QTableWidgetItem(tr(it->m_FileName));
        newItem1->setTextAlignment(Qt::AlignLeft|Qt::AlignVCenter);
        this->setItem(rowNum, 0, newItem1);

        // color it
        if (it->GetValidity()==0) newItem1->setBackgroundColor(QColor(255,0,0,50));
        else if (it->GetValidity()==1) newItem1->setBackgroundColor(QColor(0,255,0,40));
        else if (it->GetValidity()==2) newItem1->setBackgroundColor(QColor(255,255,0,40));


        // create the second column
        // it can be a parameter or a progress bar
        if (it->GetDownloadingState() == 1)
        {
            QProgressBar* newProgress = new QProgressBar();
            newProgress->setMaximum(100);
            newProgress->setMinimum(0);
            newProgress->setAlignment(Qt::AlignCenter|Qt::AlignHCenter);
            this->setCellWidget(rowNum, 1, newProgress);
            m_CurrentProgressBar = newProgress;
            atLeastOneDownloading = true;
        }
        else  // if the current file is not downloading
        {
            QString durationString;
            durationString = QString("%1").arg((int)(it->m_Duration), 0, 10);
            QTableWidgetItem *newItem2 = new QTableWidgetItem(durationString);
            newItem2->setTextAlignment(Qt::AlignHCenter|Qt::AlignVCenter);
            this->setItem(rowNum, 1, newItem2);

            // color it
            if (it->GetValidity()==0) newItem2->setBackgroundColor(QColor(255,0,0,50));
            else if (it->GetValidity()==1) newItem2->setBackgroundColor(QColor(0,255,0,40));
            else if (it->GetValidity()==2) newItem2->setBackgroundColor(QColor(255,255,0,40));
        }

        this->setRowHeight(rowNum,22);
    }

    // suddenly one of the files starts to download
    if (!m_downloading && atLeastOneDownloading)
    {
        m_downloading = true;
    }
    else if (m_downloading && !atLeastOneDownloading)
    {
        m_downloading = false;
        m_CurrentProgressBar = NULL;
    }

    QStringList horizonalHeaders;
    horizonalHeaders << "Name" << "Duration";
    this->setHorizontalHeaderLabels ( horizonalHeaders );
}

//_______________________________________________________________________________
QString QAfarsekFileList::DeleteSelectedFile ( void )
{
    m_CurrentlyEdittedName.clear();
    if (this->selectedItems().count()==0)
        return QString("");

    QString selectedItem = this->selectedItems().first()->text();
    UpdateFileList();

    return selectedItem;
}

//_________________________________________________________________________
void QAfarsekFileList::SetCurrentDeviceNumber(int number)
{
    m_currentEdittedDevice = number;
}

//_________________________________________________________________________
void QAfarsekFileList::on_cellChanged(int row, int column)
{
    if (m_CurrentlyEdittedName.count() == 0)
        return;

    if (column == 0)        // file name has changed
    {
        QTableWidgetItem changedItem(*(this->itemAt(column, row)));

        m_fileSystem->ChangeFileName (m_CurrentlyEdittedName.toAscii().data(),
                                      this->selectedItems().first()->text().toAscii().data());
        m_CurrentlyEdittedName.clear();
        UpdateFileList();

    }
    else if (column == 1)   // duration has been changed
    {
        QString selectedItem = this->selectedItems().last()->text();

        bool convertedOK;
        int newDuration = selectedItem.toInt(&convertedOK,10);

        if (!convertedOK||newDuration<1||newDuration>255)
        {
            QMessageBox msgBox;

            msgBox.setWindowTitle(tr("Error"));
            msgBox.setText(tr("The duration parameter should be an integer between 1-255."));
            msgBox.exec();
            m_CurrentlyEdittedName.clear();
            UpdateFileList();
            return;
        }

        m_fileSystem->SetFileDuration(this->selectedItems().first()->text().toAscii().data(),
                                      newDuration);
        m_CurrentlyEdittedName.clear();
        UpdateFileList();
    }
}

//_________________________________________________________________________
void QAfarsekFileList::on_cellDoubleClicked(int row, int column)
{
    QString selectedItem = this->selectedItems().first()->text();

    m_CurrentlyEdittedName = selectedItem;
}

//_________________________________________________________________________
void QAfarsekFileList::do_UpdateProgressBar ( int address, int progress )
{
    if (address == m_currentEdittedDevice)
        m_progressVal = progress;
}

//_________________________________________________________________________
void QAfarsekFileList::do_UpdateFileList ( void )
{
    this->UpdateFileList();
}

//_________________________________________________________________________
void QAfarsekFileList::on_TimerUpdate (void)
{
    if (m_progressVal >=0 && m_progressVal <= 100 && m_downloading)
    {
        if (m_CurrentProgressBar!=NULL)
        {
            m_CurrentProgressBar->setValue(m_progressVal);
        }
    }
}
